<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告条 -->
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col class="selectCate">请选择商品分类: </el-col>
        <!-- 级联选择器 -->
        <el-cascader
          v-model="selectedCateKeys"
          :options="cateList"
          :props="{ expandTrigger: 'hover', ...cascaderProps }"
          @change="handleChange"
        ></el-cascader>
        <!-- 添加参数按钮 -->
        <el-button
          class="addBtn"
          type="primary"
          @click="addDialogVisible = true"
          :disabled="TabsIsDisabled"
          >添加参数</el-button
        >
      </el-row>

      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="HandleTabsClick">
        <el-tab-pane label="动态参数" name="many" :disabled="TabsIsDisabled">
          <!-- 表格 -->
          <el-table :data="manyTableData" style="width: 100%" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :index="index"
                  closable
                  @close="handleClose(scope.row, index)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              width="50"
              label="#"
            ></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger "
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" :disabled="TabsIsDisabled">
          <!-- 表格 -->
          <el-table :data="onlyTableData" style="width: 100%" stripe>
            <el-table-column
              type="index"
              width="50"
              label="#"
            ></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column
              prop="attr_vals"
              label="参数详情"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger "
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table></el-tab-pane
        >
      </el-tabs>
    </el-card>
    <!-- 添加参数dialog -->
    <el-dialog
      :title="titleText"
      :visible.sync="addDialogVisible"
      width="45%"
      @close="addDialogClose"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsrules"
        ref="addParamsRef"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item
          v-if="this.activeName === 'only'"
          label="参数详情"
          prop="attr_vals"
        >
          <el-input v-model="addParamsForm.attr_vals"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数dialog -->
    <el-dialog
      :title="titleText"
      :visible.sync="editDialogVisible"
      width="45%"
      @close="editDialogClose"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsrules"
        ref="editParamsRef"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item
          v-if="activeName === 'only'"
          label="参数详情"
          prop="attr_vals"
        >
          <el-input v-model="editParamsForm.attr_vals"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      cateList: [],
      selectedCateKeys: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      activeName: 'many',
      addDialogVisible: false,
      deleteDialogVisible: false,
      editDialogVisible: false,
      manyTableData: [],
      onlyTableData: [],
      addParamsForm: {
        attr_name: '',
        attr_vals: '',
      },
      editParamsForm: {
        attr_name: '',
        attr_vals: '',
      },
      addParamsrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 2,
            max: 15,
            message: '长度在 2 到 15 个字符',
            trigger: 'blur',
          },
        ],
        attr_vals: [
          { required: false, message: '请输入参数详情', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 2 到 15 个字符',
            trigger: 'blur',
          },
        ],
      },
      editParamsrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          {
            min: 2,
            max: 15,
            message: '长度在 2 到 15 个字符',
            trigger: 'blur',
          },
        ],
        attr_vals: [
          { required: false, message: '请输入参数详情', trigger: 'blur' },
          {
            min: 2,
            max: 15,
            message: '长度在 2 到 15 个字符',
            trigger: 'blur',
          },
        ],
      },
      editParamsInfo: {},
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    // 当选择商品分类发生改变时调用
    handleChange() {
      // 只允许为第三级分类设置相关参数，判断是否为第三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        this.$message.warning('只允许为第三级分类设置相关参数！')
      } else {
        this.getParamsData()
      }
    },
    // 点击tabs时调用
    HandleTabsClick() {
      this.getParamsData()
    },
    // 获取参数列表数据
    async getParamsData() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      )
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputValue = ''
        item.inputVisible = false
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      }
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },
    // 添加参数
    addParams() {
      this.$refs.addParamsRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.addParamsForm.attr_vals,
          }
        )
        if (res.meta.status !== 201) {
          return this, $message.error(res.meta.msg)
        }
        this.getParamsData()
        this.addDialogVisible = false
        this.$message.success(res.meta.msg)
      })
    },
    // 关闭添加参数dialog
    addDialogClose() {
      this.$refs.addParamsRef.resetFields()
    },
    // 关闭修改参数dislog
    editDialogClose() {
      this.$refs.editParamsRef.resetFields()
    },
    // 删除参数
    deleteParams(info) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${info.cat_id}/attributes/${info.attr_id}`
          )
          console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.getParamsData()
          this.$message.success(res.meta.msg)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 显示修改参数dialog
    async showEditDialog(info) {
      this.editDialogVisible = true
      this.editParamsInfo = info
      const { data: res } = await this.$http.get(
        `categories/${info.cat_id}/attributes/${info.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editParamsForm.attr_name = res.data.attr_name
      this.editParamsForm.attr_vals = res.data.attr_vals
    },
    //
    saveEditParams() {},
    // 编辑参数
    editParams() {
      this.$refs.editParamsRef.validate(async (val) => {
        if (!val) return
        const { data: res } = await this.$http.put(
          `categories/${this.editParamsInfo.cat_id}/attributes/${this.editParamsInfo.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editParamsForm.attr_vals,
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success('修改成功')
      })
    },
    //文本框失去焦点，按下enter都会触发
    async handleInputConfirm(info) {
      if (info.inputValue.trim().length === 0) {
        info.inputValue = ''
        info.inputVisible = false
        return
      }
      info.attr_vals.push(info.inputValue.trim())
      info.inputValue = ''
      info.inputVisible = false
      // 发起网络请求，保存这次操作
      this.saveAttrVals(info)
    },
    //点击按钮，展示文本输入框
    showInput(info) {
      info.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 解决代码复用问题，删除添加属性详情方法一样
    async saveAttrVals(info) {
      const { data: res } = await this.$http.put(
        `categories/${info.cat_id}/attributes/${info.attr_id}`,
        {
          attr_name: info.attr_name,
          attr_sel: info.attr_sel,
          attr_vals: info.attr_vals.join(','),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editDialogVisible = false
      this.$message.success('修改参数详情成功')
    },
    // 删除对应参数的可选项
    handleClose(info, index) {
      info.attr_vals.splice(index)
      this.saveAttrVals(info)
    },
  },
  computed: {
    // 动态决定tabs的禁止属性
    TabsIsDisabled() {
      return this.selectedCateKeys.length !== 3
    },
    // 动态获取分类id
    cateId() {
      return this.selectedCateKeys[this.selectedCateKeys.length - 1]
    },
    // 动态决定添加参数dialog标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      if (this.activeName === 'only') {
        return '静态属性'
      }
    },
  },
}
</script>

<style scoped>
.selectCate {
  margin: 10px;
}
.addBtn {
  float: right;
  margin-right: 50px;
}
.el-tabs {
  margin-top: 15px;
}
.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
